package com.javabaas.server.novel_server.hotWords.service;

import com.javabaas.server.novel_server.common.Constant;
import com.javabaas.server.novel_server.common.ModuleCode;
import com.javabaas.server.novel_server.common.ResponseJson;
import com.javabaas.server.novel_server.common.StatusCode;
import com.javabaas.server.novel_server.hotWords.entity.HotWords;
import com.javabaas.server.novel_server.hotWords.entity.HotWordsRepository;
import com.mongodb.WriteResult;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class HotWordService {

    @Autowired
    HotWordsRepository repository;

    @Autowired
    MongoTemplate mongoTemplate;

    private final Logger logger = Logger.getLogger(getClass());


    /**
     *
     * 查询搜索热词 limit = PAGE_SIZE_MAX
     */
    public Object searchHotWords() {
        Sort sort = new Sort(Sort.Direction.DESC, "count", "createTime");
        PageRequest pageRequest = new PageRequest(0, Constant.PAGE_SIZE_MAX, sort);
        Page<HotWords> hotWordsPage = repository.findAll(pageRequest);
        List<String> keyWords = new ArrayList<>();
        for (HotWords hw: hotWordsPage.getContent()) {
            keyWords.add(hw.getHotWord());
        }
        return ResponseJson.getResponseJson(ModuleCode.MODULE_HOT_WORDS_STATUS, StatusCode.STATUS_OK, keyWords);
    }


    /**
     * 上传热搜词
     *
     * @param hotWord 热搜词
     */
    public boolean uploadHotWords(String hotWord) {
        HotWords dbHotWords = repository.findByHotWord(hotWord);
        if (dbHotWords != null) {
            Criteria criteria = Criteria.where("_id").is(dbHotWords.get_id());
            Query query = new Query(criteria);
            Update update = new Update().inc("count", 1);
            WriteResult new_hotWords = mongoTemplate.updateMulti(query, update, HotWords.class);
            return true;
        }else {
            HotWords hw = new HotWords();
            hw.setHotWord(hotWord);
            hw.setCount(1);
            hw.setCreateTime(System.currentTimeMillis());
            repository.save(hw);
            return true;
        }
    }





}
